import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/models/common/StatusMessageResult.dart';
import 'package:ichinesereader/models/student/assessmentsResult.dart';
import 'package:ichinesereader/models/student/Assignments.dart';
import 'package:ichinesereader/models/student/AssignmentDetail.dart';
import 'package:ichinesereader/models/teacher/AssignmentType.dart';
import 'package:ichinesereader/models/teacher/assignmentDto.dart';
import 'package:ichinesereader/service/schooladmin.dart';
import 'package:ichinesereader/service/student.dart';
import 'package:ichinesereader/utils/log.dart';

class HomeworksController extends GetxController with StateMixin<dynamic> {
  SchoolAdminServiceProvider _schoolAdminServiceProvider =
      new SchoolAdminServiceProvider();
  StudentServiceProvider _studentServiceProvider = new StudentServiceProvider();

  Rx<StatusMessageResult> _statusMessageResult =
      Rx<StatusMessageResult>(StatusMessageResult());
  Rx<StatusMessageResult> get statusMessageResult => this._statusMessageResult;

  List<AssignmentDetail> _assignmentItems = <AssignmentDetail>[].obs;
  List<Assignment> _liveAssignments = <Assignment>[].obs;

  List<AssignmentDetail> get assignmentItems => this._assignmentItems;
  List<Assignment> get liveAssignments => this._liveAssignments;

  List<Assignment> _myAssignments = <Assignment>[].obs;
  List<Assignment> get myAssignments => this._myAssignments;

  List<Assignment> _assignmentRecords = <Assignment>[].obs;
  List<Assignment> get assignmentRecords => this._assignmentRecords;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  dispose() {
    super.dispose();
  }

  Future<List<AssignmentDetail>> fetchTeacherHomworks(
      String classId, AssignmentType at) async {
    try {
      EasyLoading.show();
      _assignmentItems.clear();
      var response = await _schoolAdminServiceProvider.getAllAssignmentsByClass(
          classId, at);
      if (response.statusCode == 200) {
        var data = assignmentDetailsFromJson(response.bodyString);
        _assignmentItems.assignAll(data);
        //if (_assignmentItems.length > 0)
        change(_assignmentItems, status: RxStatus.success());
        //else
        //  change(null, status: RxStatus.empty());
      } else {
        change(_assignmentItems, status: RxStatus.success());
        //change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
        Log.debug(response.body);
      }
    } catch (error) {
      change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return _assignmentItems;
  }

  Future<StatusMessageResult> deleteHomeworkByClassId(
      String classId, String assignmentId) async {
    var _statusMessage = StatusMessageResult();
    try {
      EasyLoading.show();
      var response = await _schoolAdminServiceProvider.deleteAssignment(
          classId, assignmentId);
      if (response.statusCode == 200) {
        _statusMessage.status = 1000;
        this
            ._assignmentItems
            .removeWhere((element) => element.id == assignmentId);
        change(_assignmentItems, status: RxStatus.success());
      }
    } catch (error) {
      _statusMessage.status = 0;
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusMessage;
  }

  // void fetchStudentHomeworks(String classId) async {
  //   try {
  //     var response = await _studentServiceProvider.getLiveAssignments(classId);
  //     //Log.debug(response.body);
  //     if (response.statusCode == 200) {
  //       var data = studentAssessmentsFromJson(response.body);
  //       Log.debug(data.list?.length ?? '0 faound');
  //       List<Assignment> items = data.list as List<Assignment>;
  //       items.sort((a, b) {
  //         int end1 = a.assignment!.endDateUtc!.toInt();
  //         var end2 = b.assignment!.endDateUtc!.toInt();
  //         return end1.compareTo(end2);
  //       });
  //       _liveAssignments.assignAll(items);

  //       if (_liveAssignments.length > 0) {
  //         change(_liveAssignments, status: RxStatus.success());
  //       } else {
  //         change(null, status: RxStatus.empty());
  //       }
  //     } else {
  //       change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
  //       Log.debug(response.body);
  //     }
  //   } catch (error) {
  //     change(null, status: RxStatus.error('Oops, something wrong ...'.tr));
  //     Log.debug(error);
  //   }
  // }

  Future<List<Assignment>> fetchStudentLiveHomeworks(String classId) async {
    List<Assignment> assignments = [];
    try {
      EasyLoading.show();
      var response = await _studentServiceProvider.getLiveAssignments(classId);
      if (response.statusCode == 200) {
        var data = assignmentsFromJson(response.body);
        Log.debug(data.length);
        _liveAssignments.assignAll(data);
        if (_liveAssignments.length > 0) {
          assignments = data;
          change(_liveAssignments, status: RxStatus.success());
        } else
          change(_liveAssignments, status: RxStatus.empty());
      } else {
        change(null, status: RxStatus.error());
      }
    } catch (error) {
      change(null, status: RxStatus.error());
    } finally {
      EasyLoading.dismiss();
    }
    return assignments;
  }

  void fetchStudentHomeworkRecordsByClass(String classId) async {
    try {
      EasyLoading.show();
      var response =
          await _studentServiceProvider.getAssignmentRecordsByClass(classId);
      if (response.statusCode == 200) {
        var data = assignmentsFromJson(response.body);
        //Log.debug(data.length);
        data.sort((a, b) {
          int end1 = a.assignment!.endDateUtc!.toInt();
          var end2 = b.assignment!.endDateUtc!.toInt();
          return end2.compareTo(end1);
        });
        _assignmentRecords.assignAll(data);
        if (_assignmentRecords.isNotEmpty) {
          change(_assignmentRecords, status: RxStatus.success());
        } else {
          change(null, status: RxStatus.empty());
        }
      } else {
        change(null, status: RxStatus.error());
      }
    } catch (error) {
      change(null, status: RxStatus.error());
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  void fetchStudentMyHomeworks(String classId) async {
    try {
      change(_myAssignments, status: RxStatus.loading());
      var response = await _studentServiceProvider.getMyAssignments(classId);
      if (response.statusCode == 200) {
        var data = assignmentsFromJson(response.body);
        Log.debug(data.length);
        //List<Assignment> items = data;
        _myAssignments.assignAll(data);

        if (_myAssignments.isNotEmpty) {
          change(_myAssignments, status: RxStatus.success());
        } else {
          change(null, status: RxStatus.empty());
        }
      } else {
        change(null, status: RxStatus.empty());
      }
    } catch (error) {
      Log.debug(error);
    }
  }

  void fetchStudentHomeworkDetails(String classId, String assignmentId) async {
    var _statusResult = new StatusMessageResult();
    try {
      var response = await _studentServiceProvider.getLiveAssignmentDetails(
          classId, assignmentId);
      //Log.debug(response.body);
      if (response.statusCode == 200) {
        var data = studentAssessmentsFromJson(response.body);
        Log.debug(data.list?.length ?? '0 faound');
        List<Assignment> items = data.list as List<Assignment>;
        _liveAssignments.assignAll(items);
        _statusResult.status = 1000;
        _statusResult.message = 'Success';
      } else {
        _statusResult.status = response.statusCode;
        _statusResult.message = 'Failed';
      }
    } catch (error) {
      _statusResult.status = 0;
      _statusResult.message = 'Oops, something wrong ...'.tr;
      Log.debug(error);
    }
    _statusMessageResult.value = _statusResult;
  }

  Future<StatusMessageResult> createHomework(
      String classId, AssignmentDto dto, String? assignmentId) async {
    var _statusResult = new StatusMessageResult();
    try {
      EasyLoading.show();
      var response = await _schoolAdminServiceProvider.createAssignment(
          classId, dto, assignmentId);
      if (response.statusCode == 200) {
        _statusResult.status = 1000;
        _statusResult.message = 'Success';
      } else {
        _statusResult.status = response.statusCode;
        _statusResult.message = 'Failed';
      }
    } catch (error) {
      _statusResult.status = 0;
      _statusResult.message = 'Oops, something wrong ...'.tr;
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
    return _statusResult;
  }
}
